﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Net.Http;
using System.Text;
using System.Threading.Tasks;

namespace WpfApp1
{
    public class HttpTool
    {
        public static async Task<string> PostDataAsync(string url, string jsonData,Dictionary<string,string> headers)
        {
            using (var client = new HttpClient())
            {
                // 设置请求的内容类型为JSON
                client.DefaultRequestHeaders.Accept.Clear();
                client.DefaultRequestHeaders.Accept.Add(new System.Net.Http.Headers.MediaTypeWithQualityHeaderValue("application/json"));
                if(headers!=null)
                {
                    foreach (var item in headers)
                    {
                        client.DefaultRequestHeaders.Add(item.Key, item.Value);
                    }
                }

                // 将JSON数据转换为HttpContent
                HttpContent content = new StringContent(jsonData, Encoding.UTF8, "application/json");

                // 发送POST请求
                HttpResponseMessage response = await client.PostAsync(url, content);

                // 读取响应内容
                if (response.IsSuccessStatusCode)
                {
                    string responseData = await response.Content.ReadAsStringAsync();
                    return responseData;
                    //Console.WriteLine("Response received successfully:");
                    //Console.WriteLine(responseData);
                }
                else
                {
                    return "";
                }
            }
        }
    }
}
